package com.smart.stock.module.maindata.services;

import com.alibaba.fastjson.JSONArray;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.result.DeleteResult;
import com.smart.stock.common.util.spring.SpringContextUtil;
import com.smart.stock.module.maindata.entity.StockPriceDaily;
import com.smart.stock.module.spider.jobSpiderApi.XueQiuApi;
import com.smart.stock.module.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 每日指数数据
 * add by andrew
 */
@Slf4j
@Service
public class StockDailyIndexesService {
    @Autowired
    private MongoTemplate template;

    public MongoTemplate getMongoTemp() {
        return SpringContextUtil.getBean(MongoTemplate.class);
    }
    /**
     * 刷新所有股票的日线数据
     */
    /**
     * 刷新所有股票的日线数据
     */
    public void refreshDailyIndexes(){
        XueQiuApi xueQiu = new XueQiuApi();
        refreshDailyIndexes(xueQiu.getIndexSH(),GlobalConstant.INDEX_SH);
        refreshDailyIndexes(xueQiu.getIndexSZ(),GlobalConstant.INDEX_SZ);
        refreshDailyIndexes(xueQiu.getIndexCYB(),GlobalConstant.INDEX_CYB);
        refreshDailyIndexes(xueQiu.getIndexKCB(),GlobalConstant.INDEX_KCB);
    }
    public void refreshDailyIndexes(List<JSONArray> indexData,String code) {
        if (indexData.size()>0) {
            DeleteResult deleteResult = getMongoTemp().remove(new Query(Criteria.where("code").is(code)), "stock_price_daily");
            JSONArray meta = indexData.get(0);
            JSONArray data = indexData.get(1);
            BulkOperations ops = getMongoTemp().bulkOps(BulkOperations.BulkMode.UNORDERED, "stock_price_daily");
            StockPriceDaily dailyIndexes;
            for (int i = 0; i < data.size(); i++) {
                JSONArray row = data.getJSONArray(i);
                dailyIndexes = new StockPriceDaily();
                dailyIndexes.setCode(code);
                dailyIndexes.setTradeDate(row.getInteger(0));
                dailyIndexes.setVol(row.getDouble(1));
                dailyIndexes.setOpen(row.getDouble(2));
                dailyIndexes.setHigh(row.getDouble(3));
                dailyIndexes.setLow(row.getDouble(4));
                dailyIndexes.setClose(row.getDouble(5));
                dailyIndexes.setChange(row.getDouble(6));
                dailyIndexes.setPctchg(row.getDouble(7));
                dailyIndexes.setTurnoverrate(row.getDouble(8));
                dailyIndexes.setAmount(row.getDouble(9));
                ops.insert(dailyIndexes);
            }
            BulkWriteResult bulkWriteResult = ops.execute();

            //维护代码表中的更新时间字段
//            UpdateResult updateResult2 = getMongoTemp().upsert(
//                    new Query(Criteria.where("_id").is(currentCodeInfo.getCode())),
//                    new Update().set("dailyDate", Integer.valueOf(TradingDateUtil.getDateYYYYMMdd())), "stock_price_daily");
//
//            log.info("insert: {},update: {} delete: {}", bulkWriteResult.getInsertedCount(), updateResult2.getModifiedCount(), deleteResult.getDeletedCount());
        }
//        template.insertAll(list);
    }

    /**
     * 统计日线数据行数
     * @param code
     * @return
     */
    public Long getStockDailyIndexesRows(String code){
        return template.count(new Query(Criteria.where("code").is(code)), StockPriceDaily.class);
    }

    /**
     * 得到日线数据
     * @param code
     * @return
     */
    public List<StockPriceDaily> getDailyIndexesLine(String code){
        return template.find(new Query(Criteria.where("code").is(code)).with(Sort.by(Sort.Direction.ASC, "tradeDate")),StockPriceDaily.class);
    }
}
